<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="客户" prop="customerId">
        <el-input
          v-model="queryParams.customerId"
          placeholder="请输入客户"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单金额" prop="receivableAmount">
        <el-input
          v-model="queryParams.receivableAmount"
          placeholder="请输入订单金额"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="出库单状态" prop="shipmentOrderStatus">
        <el-select v-model="queryParams.shipmentOrderStatus" placeholder="请选择出库单状态" clearable>
          <el-option
            v-for="dict in outstatus"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="审核人" prop="checkUserId">
        <el-input
          v-model="queryParams.checkUserId"
          placeholder="请输入审核人"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="审核时间" prop="checkTime">
        <el-date-picker clearable
          v-model="queryParams.checkTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择审核时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['order:outbound:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['order:outbound:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['order:outbound:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['order:outbound:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="outboundList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
<!--      <el-table-column label="${comment}" align="center" prop="id" />-->
      <el-table-column label="出库单号" align="center" prop="shipmentOrderNo" />
      <el-table-column label="出库类型" align="center" prop="shipmentOrderType" />
      <el-table-column label="出库订单" align="center" prop="orderNo" />
      <el-table-column label="客户" align="center" prop="customerId" />
      <el-table-column label="订单金额" align="center" prop="receivableAmount" />
      <el-table-column label="出库状态" align="center" prop="shipmentOrderStatus">
        <template #default="scope">
          <dict-tag :options="outstatus" :value="scope.row.shipmentOrderStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="审核状态" align="center" prop="checkStatus" />
      <el-table-column label="审核人" align="center" prop="checkUserId" />
      <el-table-column label="审核时间" align="center" prop="checkTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.checkTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="创建人" align="center" prop="createBy" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改人" align="center" prop="updateBy" />
      <el-table-column label="修改时间" align="center" prop="updateTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['order:outbound:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['order:outbound:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改销售发货出库对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="outboundRef" :model="form" :rules="rules" label-width="80px">
<!--        <el-form-item label="出库单号" prop="shipmentOrderNo">-->
<!--          <el-input v-model="form.shipmentOrderNo" placeholder="请输入出库单号，系统自动生成" />-->
<!--        </el-form-item>-->
        <el-form-item label="出库订单" prop="orderNo">
          <el-input v-model="form.orderNo" placeholder="请输入出库订单" />
        </el-form-item>
        <el-form-item label="客户" prop="customerId">
          <el-input v-model="form.customerId" placeholder="请输入客户" />
        </el-form-item>
        <el-form-item label="订单金额" prop="receivableAmount">
          <el-input v-model="form.receivableAmount" placeholder="请输入订单金额" />
        </el-form-item>
<!--        <el-form-item label="出库单状态" prop="shipmentOrderStatus">-->
<!--          <el-select v-model="form.shipmentOrderStatus" placeholder="请选择出库单状态">-->
<!--            <el-option-->
<!--              v-for="dict in outstatus"-->
<!--              :key="dict.value"-->
<!--              :label="dict.label"-->
<!--              :value="parseInt(dict.value)"-->
<!--            ></el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="审核人" prop="checkUserId">-->
<!--          <el-input v-model="form.checkUserId" placeholder="请输入审核人" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="审核时间" prop="checkTime">-->
<!--          <el-date-picker clearable-->
<!--            v-model="form.checkTime"-->
<!--            type="date"-->
<!--            value-format="YYYY-MM-DD"-->
<!--            placeholder="请选择审核时间">-->
<!--          </el-date-picker>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="波次号" prop="waveNo">-->
<!--          <el-input v-model="form.waveNo" placeholder="请输入波次号" />-->
<!--        </el-form-item>-->
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
<!--        <el-form-item label="删除标识" prop="delFlag">-->
<!--          <el-input v-model="form.delFlag" placeholder="请输入删除标识" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="前置单据id" prop="orderId">-->
<!--          <el-input v-model="form.orderId" placeholder="请输入前置单据id" />-->
<!--        </el-form-item>-->
        <el-divider content-position="center">出库单详情信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" @click="handleAddWmsShipmentOrderDetail">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="Delete" @click="handleDeleteWmsShipmentOrderDetail">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="wmsShipmentOrderDetailList" :row-class-name="rowWmsShipmentOrderDetailIndex" @selection-change="handleWmsShipmentOrderDetailSelectionChange" ref="wmsShipmentOrderDetail">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="物料" prop="itemId" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.itemId" placeholder="请输入物料" />
            </template>
          </el-table-column>
          <el-table-column label="计划数量" prop="planQuantity" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.planQuantity" placeholder="请输入计划数量" />
            </template>
          </el-table-column>
          <el-table-column label="实际数量" prop="realQuantity" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.realQuantity" placeholder="请输入实际数量" />
            </template>
          </el-table-column>
          <el-table-column label="货架" prop="rackId" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.rackId" placeholder="请输入货架" />
            </template>
          </el-table-column>
          <el-table-column label="金额" prop="money" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.money" placeholder="请输入金额" />
            </template>
          </el-table-column>
          <el-table-column label="备注" prop="remark" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.remark" placeholder="请输入备注" />
            </template>
          </el-table-column>
          <el-table-column label="所属仓库" prop="warehouseId" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.warehouseId" placeholder="请输入所属仓库" />
            </template>
          </el-table-column>
          <el-table-column label="所属库区" prop="areaId" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.areaId" placeholder="请输入所属库区" />
            </template>
          </el-table-column>
          <el-table-column label="出库状态" prop="shipmentOrderStatus" width="150">
            <template #default="scope">
              <el-select v-model="scope.row.shipmentOrderStatus" placeholder="请选择出库状态">
                <el-option label="请选择字典生成" value="" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="箱号id" prop="boxId" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.boxId" placeholder="请输入箱号id" />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>


    <!--物料弹窗-->

    <el-dialog v-model="dialogVisible" title="物料管理" width="1100" draggable>
      <el-table v-loading="loading1" :data="orderList" @selection-change="handleSelectionChange1">
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="编号" align="center" prop="id"/>
        <el-table-column label="货号" align="center" prop="itemNo"/>
        <el-table-column label="名称" align="center" prop="itemName"/>
        <el-table-column label="规格" align="center" prop="specification"/>
        <el-table-column label="分类" align="center" prop="itemType"/>
        <el-table-column label="单位" align="center" prop="unit"/>
        <el-table-column label="单价" align="center" prop="unitPrice"/>
        <el-table-column label="所属货架" align="center" prop="rackId"/>
        <el-table-column label="库区编号" align="center" prop="areaId"/>
        <el-table-column label="所属仓库" align="center" prop="warehouseId"/>
        <el-table-column label="安全库存" align="center" prop="quantity"/>
        <el-table-column label="生产日期" align="center" prop="productionDate" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.productionDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="有效期" align="center" prop="expiryDate" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.expiryDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="批次" align="center" prop="batch"/>
        <el-table-column label="备注" align="center" prop="remark"/>
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
      </el-table>
      <pagination
          v-show="total1>0"
          :total="total1"
          v-model:page="queryParams1.pageNum"
          v-model:limit="queryParams1.pageSize"
          @pagination="getItemList"
      />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="itemSubmit()">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Outbound">
import {listItem, getItem, delItem, addItem, updateItem} from "@/api/system/item";
import { listOutbound, getOutbound, delOutbound, addOutbound, updateOutbound } from "@/api/order/outbound";
import {ref} from "vue";
const dialogVisible = ref(false)
const { proxy } = getCurrentInstance();
const { outstatus } = proxy.useDict('outstatus');

const outboundList = ref([]);
const wmsShipmentOrderDetailList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const checkedWmsShipmentOrderDetail = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
//物料弹窗
const orderList = ref([]);

const loading1 = ref(true);
const total1 = ref(0);
const supplierId = ref();
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    shipmentOrderNo: null,
    shipmentOrderType: null,
    orderNo: null,
    customerId: null,
    receivableAmount: null,
    shipmentOrderStatus: null,
    checkStatus: null,
    checkUserId: null,
    checkTime: null,
  },
  rules: {
    delFlag: [
      { required: true, message: "删除标识不能为空", trigger: "blur" }
    ],
    orderId: [
      { required: true, message: "前置单据id不能为空", trigger: "blur" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询销售发货出库列表 */
function getList() {
  loading.value = true;
  listOutbound(queryParams.value).then(response => {
    outboundList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    shipmentOrderNo: null,
    shipmentOrderType: null,
    orderNo: null,
    customerId: null,
    receivableAmount: null,
    shipmentOrderStatus: null,
    checkStatus: null,
    checkUserId: null,
    checkTime: null,
    waveNo: null,
    remark: null,
    delFlag: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    orderId: null
  };
  wmsShipmentOrderDetailList.value = [];
  proxy.resetForm("outboundRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}





const data1 = reactive({
  form1: {},
  // queryParams1物料弹窗分页参数
  queryParams1: {
    pageNum: 1,
    pageSize: 10,
    itemNo: null,
    itemName: null,
    itemType: null,
    rackId: null,
    areaId: null,
    warehouseId: null,
    createTime: null,
  }, rules1: {}
});
const {queryParams1, form1, rules1} = toRefs(data1);

/** 查询物料列表 */
function getorderList() {
  loading1.value = true;
  outInListPurchaseOrder(queryParams1.value).then(response => {
    orderList.value = response.rows;
    total1.value = response.total;
    loading1.value = false;
    console.log("物料：" + orderList.value[0].itemNo)
  });
}

//存储物料弹窗被选中的数据
const ids1 = ref([]);
//物料弹窗选中状态变量
const single1 = ref(true);
const multiple1 = ref(true);

// 多选框选中数据物料弹窗
function handleSelectionChange1(selection) {
  ids1.value = selection.map(item => {
    let re = {};
    re.itemId = item.id;
    re.itemName = item.itemName;
    re.itemNo = item.itemNo;
    return re;
  });
  single1.value = selection.length != 1;
  multiple1.value = !selection.length;
}


//物料弹窗确认按钮
const itemSubmit = () => {

  for (let item of ids1.value) {
    //判断物料是否已存在
    if (isObjectInArray(checkedWmsPurchaseorderDetail.value, item, 'itemId')) {
      ElMessage.error("该物料已存在")
    } else {//不存在，则追加物料到checkedWmsPurchaseorderDetail中并关闭物料弹框
      checkedWmsPurchaseorderDetail.value.push(item);
      dialogVisible.value = false;
      single1.value = false;
      multiple1.value = false;
    }
  }

}


/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加销售发货出库";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getOutbound(_id).then(response => {
    form.value = response.data;
    wmsShipmentOrderDetailList.value = response.data.wmsShipmentOrderDetailList;
    open.value = true;
    title.value = "修改销售发货出库";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["outboundRef"].validate(valid => {
    if (valid) {
      form.value.wmsShipmentOrderDetailList = wmsShipmentOrderDetailList.value;
      if (form.value.id != null) {
        updateOutbound(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addOutbound(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除销售发货出库编号为"' + _ids + '"的数据项？').then(function() {
    return delOutbound(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 出库单详情序号 */
function rowWmsShipmentOrderDetailIndex({ row, rowIndex }) {
  row.index = rowIndex + 1;
}




/** 出库单详情添加按钮操作 */
function handleAddWmsShipmentOrderDetail() {
  let obj = {};
  obj.itemId = "";
  obj.planQuantity = "";
  obj.realQuantity = "";
  obj.rackId = "";
  obj.money = "";
  obj.remark = "";
  obj.warehouseId = "";
  obj.areaId = "";
  obj.shipmentOrderStatus = "";
  obj.boxId = "";
  wmsShipmentOrderDetailList.value.push(obj);
  dialogVisible.value = true;

}

/** 出库单详情删除按钮操作 */
function handleDeleteWmsShipmentOrderDetail() {
  if (checkedWmsShipmentOrderDetail.value.length == 0) {
    proxy.$modal.msgError("请先选择要删除的出库单详情数据");
  } else {
    const wmsShipmentOrderDetails = wmsShipmentOrderDetailList.value;
    const checkedWmsShipmentOrderDetails = checkedWmsShipmentOrderDetail.value;
    wmsShipmentOrderDetailList.value = wmsShipmentOrderDetails.filter(function(item) {
      return checkedWmsShipmentOrderDetails.indexOf(item.index) == -1
    });
  }
}

/** 复选框选中数据 */
function handleWmsShipmentOrderDetailSelectionChange(selection) {
  checkedWmsShipmentOrderDetail.value = selection.map(item => item.index)
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('order/outbound/export', {
    ...queryParams.value
  }, `outbound_${new Date().getTime()}.xlsx`)
}

getList();
</script>
